package com.usooft.metaTalent.admin.base;

import com.usooft.framework.web.auth.AbstractAuthenticationInterceptor;
import com.usooft.metaTalent.core.system.entity.Employee;
import com.usooft.metaTalent.core.system.service.EmployeeRoleService;
import com.usooft.metaTalent.core.system.service.EmployeeService;
import com.usooft.metaTalent.core.system.service.RolePermissionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.stream.Collectors;

@Component
@Slf4j
@RequiredArgsConstructor
public class EmployeeAuthenticationInterceptor extends AbstractAuthenticationInterceptor<Employee> {

    private final EmployeeService employeeService;
    private final EmployeeRoleService employeeRoleService;
    private final RolePermissionService rolePermissionService;

    @Override
    public Employee get(Serializable serializable) {
        return employeeService.get((Long) serializable);
    }

    @Override
    public boolean check(Employee employee, String permission) {
        if (employee.getLocked()) {
            return false;
        }
        if (employee.getAdmin()) {
            return true;
        }
        if (permission == null) {
            return true;
        }
        return employeeRoleService.listRoleIds(employee)
                .stream()
                .flatMap(roleId -> rolePermissionService.listPermissionsByRoleId(roleId).stream())
                .collect(Collectors.toSet())
                .contains(permission);
    }

}